'use strict'

var fs = require('fs')
var path = require('path')
var mongoose = require('mongoose')

// 作用是去除 DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead. 提示
mongoose.set('useCreateIndex', true);
// 连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/management', {useNewUrlParser: true},function(err) {
  if(err){
    console.log(err);
    console.log('连接失败');
  }else{
      console.log('连接成功');
  }
});

// 循环引入创建 models 下面的表
var models_path = path.join(__dirname, '/app/models')
var walk = function(modelPath) {
  fs
    .readdirSync(modelPath)
    .forEach(function(file) {
      var filePath = path.join(modelPath, '/' + file)
      var stat = fs.statSync(filePath)

      if (stat.isFile()) {
        if (/(.*)\.(js|coffee)/.test(file)) {
          require(filePath)
        }
      }
      else if (stat.isDirectory()) {
        walk(filePath)
      }
    })
}
walk(models_path)

var koa2 = require('koa2')
var logger = require('koa-logger')
var session = require('koa-session2')
var bodyParser = require('koa-bodyparser')
// const serve = require('koa-static');
const koaBody = require('koa-body');
var app = new koa2()

app.use(logger())
app.use(session({
  key: "SESSIONID",
  httpOnly: false
}))
// app.use(bodyParser())
app.use(koaBody({
  multipart: true
}))
//登陆拦截
// app.use(async (ctx, next) => {
//   // ctx.cookies.get('SESSIONID') ctx.session.user
//   if(!ctx.cookies.get('SESSIONID') && ctx.path !== '/api/login/'){
//     ctx.body = {
//       success: false,
//       message: '用户未登录！'
//     }
//     return;
//   }
//   await next();
// })
// 引入路由文件
var router = require('./config/routes')()

app
  .use(router.routes())
  .use(router.allowedMethods())

app.use(require('koa-static')(__dirname + '/public'));

// 监听 6789 端口
app.listen(6789)
console.log('Listening: 6789')
